<template>
    <div class="loginBackground flex jc-center ai-center vh100" :class="{focus: isFocus}">
        <loading :load="loading"></loading>
        <div class="main">
            <h1>登录</h1>
            <form @submit.prevent="login">
                <label>
                    <input type="text" v-model="model.username">
                    <span class="placeholder" v-show="model.username === ''">用户名</span>
                </label>
                <label>
                    <input type="password" v-model="model.password">
                    <span class="placeholder" v-show="model.password === ''">密码</span>
                </label>
                <button></button>
            </form>
            <div class="doBox">
                <div class="submit flex ai-center jc-center" @click="login">登录</div>
                <router-link to="/register">没有账号？点击注册</router-link>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                model: {
                    username: '',
                    password: ''
                },
                hasSubmit: false,

                isFocus: false,
                loading: false,
            }
        },
        methods: {
            async login() {
                if (!this.hasSubmit) {
                    this.hasSubmit = true;
                    if (this.model.username.length <  3) {
                        this.hasSubmit = false;
                        this.$emit('alert', '用户名不能小于3个字符！')
                        return
                    } else if (this.model.password.length < 6) {
                        this.hasSubmit = false;
                        this.$emit('alert', '密码长度不能小于6位！')
                        return
                    }
                    this.loading = true;
                    let res = await this.$http.post('/login', this.model);
                    await this.$http.post('/login', this.model);
                    this.loading = false;
                    this.hasSubmit = false;
                    sessionStorage.token = res.data.token;
                    this.$emit('alert', '登陆成功！');
                    let mobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
                    if (mobile) {
                        this.$router.push('/mobile');
                    } else {
                        this.$router.push('/');
                    }
                }
            }
        }
    }
</script>

<style scoped lang="scss" src="../css/login.scss"></style>